from rest_framework import serializers
from apps.users.models import User
from django_redis import get_redis_connection
import re


class UserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(min_length=8, max_length=20, write_only=True)
    sms_code = serializers.CharField(write_only=True)
    allow = serializers.BooleanField(write_only=True)
    class Meta:
        model = User
        fields = ['username', 'password', 'mobile', 'password2', 'email', 'email_active', 'sms_code', 'allow']
        extra_kwargs = {
            'username': {'min_length': 5, 'max_length': 20},
            'password': {'min_length': 8, 'max_length': 20, 'write_only': True}
        }

    def validate(self, attrs):
        mobile = attrs.get('mobile')
        password = attrs.get('password')
        password2 = attrs.get('password2')
        sms_code_client = attrs.get('sms_code')
        allow = attrs.get('allow')

        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms%s' % mobile)
        if not sms_code_server:
            return serializers.ValidationError('验证码过期')
        if sms_code_server.decode() != sms_code_client:
            return serializers.ValidationError('验证码错误')
        if password != password2:
            return serializers.ValidationError('密码错误')
        if allow != True:
            return serializers.ValidationError('allow参数有误')
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return serializers.ValidationError('手机号码填写有误')
        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = User.objects.create_user(**validated_data)
        return user
